package com.xzq.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/22 21:35
 * @Version 1.0.0
 **/
@Data
public class NettyServer {

    private Logger logger = LoggerFactory.getLogger(NettyServer.class);

    private ServerChannelInitializer serverChannelInitializer;

    public NettyServer(ServerChannelInitializer serverChannelInitializer) {
        this.serverChannelInitializer = serverChannelInitializer;
    }



    //Nio线程组
    private NioEventLoopGroup boss = new NioEventLoopGroup();
    private NioEventLoopGroup worker = new NioEventLoopGroup();
    private Channel channel;

    public ChannelFuture lister(InetSocketAddress address) {
        ChannelFuture f = null;
        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(serverChannelInitializer);
            logger.info("Netty服务器启动");
          f=  server.bind(address).sync();
            channel = f.channel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f;
    }

    public void destory() {
        if (channel==null){return;}
        channel.close();
        worker.shutdownGracefully();
        boss.shutdownGracefully();
    }
}
